package it.polimi.swKnights.SWIMv2.utility;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/* NB -- >
 * be carfull using .diget(), after the call the digest will be resetted!
 */

public class PasswordUtility {
	
	private MessageDigest md;
	
	public PasswordUtility() {
		try 
		{
			md = MessageDigest.getInstance("SHA-256");
		} 
		catch (NoSuchAlgorithmException e) 
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * return the hash format of the password
	 * @param password
	 * @param salt
	 * @return
	 */
	public String getEncriptedPassword(String password, String salt)
	{
		StringBuilder toEncriptPassw = new StringBuilder();
		toEncriptPassw.append(password+salt);
		md.reset();
		md.update(toEncriptPassw.toString().getBytes()); 
	
		return getStringFromByte(md.digest());
		
		
	}
	
	/**
	 * return true if the attemptedPassword is a valid one, false otherwise
	 * 
	 * The method makes the hash of the attemptedPassword with the add of the salt, and check weather
	 * the the hash is the same with the encripted password
	 * 
	 * @param attemptedPassword
	 * @param encriptedPassword
	 * @param salt
	 * @return
	 */
	public boolean autenticate(String attemptedPassword, String encriptedPassword, String salt)
	{
		StringBuilder toCheckPassw = new StringBuilder();
		toCheckPassw.append(attemptedPassword+salt);
		md.reset();
		md.update(toCheckPassw.toString().getBytes());
		String toCheckHexPasswd = getStringFromByte(md.digest()); 
		
		return toCheckHexPasswd.equals(encriptedPassword);
	}
	
	/**
	 * used to get string from a byte array
	 * @param bytePassword
	 * @return
	 */
	private String getStringFromByte(byte[] bytePassword)
	{
		StringBuffer sb = new StringBuffer();
        
		for (int i = 0; i < bytePassword.length; i++) {
         sb.append(Integer.toString((bytePassword[i] & 0xff) + 0x100, 16).substring(1));
        }
		
		return sb.toString();
           
	}
	
	
	

}
